import 'package:flutter/material.dart';


// child: CustomBarChart(
//   width: double.infinity,
//   height: 360,
//   data: [
//     BarData('1', 0.5),
//     BarData('2', 0.2),
//     BarData('3', 0.8),
//     BarData('4', -0.3),
//     BarData('5', 0.4),
//     BarData('6', -0.2),
//     BarData('7', 0.3),
//     BarData('8', -0.1),
//     BarData('9', 0.2),
//     BarData('10', -0.2),
//     BarData('11', 0.1),
//     BarData('12', 0.3),
//     BarData('13', 1.2),
//     BarData('14', 0.5),
//     BarData('15', 0.2),
//     BarData('16', 0.8),
//     BarData('17', -0.3),
//     BarData('18', 0.4),
//     BarData('19', -0.2),
//     BarData('20', 0.3),
//     BarData('21', -0.1),
//     BarData('22', 0.2),
//     BarData('23', -0.2),
//     BarData('24', 0.1),
//     BarData('25', 0.3),
//   ],
// ),

///自定义柱状统计图
class CustomBarChart extends StatefulWidget {
  final List<BarData> data;
  final double width;
  final double height;
  final Duration animationDuration;

  const CustomBarChart({
    Key? key,
    required this.data,
    this.width = 400,
    this.height = 300,
    this.animationDuration = const Duration(milliseconds: 800),
  }) : super(key: key);

  @override
  State<CustomBarChart> createState() => _CustomBarChartState();
}

class _CustomBarChartState extends State<CustomBarChart> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: widget.animationDuration,
    );
    _animation = CurvedAnimation(
      parent: _controller,
      curve: Curves.easeOutCubic,
    );
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return CustomPaint(
          size: Size(widget.width, widget.height),
          painter: BarChartPainter(
            widget.data,
            _animation.value,
          ),
        );
      },
    );
  }
}

class BarChartPainter extends CustomPainter {
  final List<BarData> data;
  final double animationValue;

  BarChartPainter(this.data, this.animationValue);

  @override
  void paint(Canvas canvas, Size size) {
    // 定义样式和边距
    const double padding = 40;
    const double barWidth = 6;
    const double barSpacing = 8;
    const double labelPadding = 10;

    // 计算可用绘图区域
    final double availableWidth = size.width - 2 * padding;
    final double availableHeight = size.height - 2 * padding;

    // 找出最大值和最小值（用于缩放）
    final double maxValue = data.map((d) => d.value).reduce((a, b) => a > b ? a : b);
    final double minValue = data.map((d) => d.value).reduce((a, b) => a < b ? a : b);

    // 确保最小值不大于0，以便正确显示负值
    final double scaledMinValue = minValue < 0 ? minValue : 0;

    // 绘制背景
    final backgroundPaint = Paint()
      ..color = Colors.transparent!
      ..style = PaintingStyle.fill;
    canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), backgroundPaint);

    // 绘制柱状图
    final barPaint = Paint()
      ..style = PaintingStyle.fill;

    final textStyle = TextStyle(
      color: Colors.white,
      fontSize: 12,
    );
    final textPainter = TextPainter(
      textDirection: TextDirection.ltr,
    );

    // 计算每个柱状图的位置
    final double totalBarWidth = data.length * (barWidth + barSpacing) - barSpacing;
    final double startX = padding + (availableWidth - totalBarWidth) / 2;

    // 计算Y轴0点位置（处理负值）
    final double zeroY = size.height - padding - (availableHeight * (-scaledMinValue) / (maxValue - scaledMinValue));

    // 绘制0点水平线
    final zeroLinePaint = Paint()
      ..color = Colors.grey
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1
      ..strokeCap = StrokeCap.round;
    canvas.drawLine(
      Offset(padding, zeroY),
      Offset(size.width - padding, zeroY),
      zeroLinePaint,
    );

    for (int i = 0; i < data.length; i++) {
      final BarData item = data[i];
      final double xPos = startX + i * (barWidth + barSpacing);

      // 根据值的正负设置颜色
      barPaint.color = item.value >= 0 ? const Color(0xFFE3C686) : const Color(0xFFEB5664);

      // 计算柱状图的高度（按比例缩放）
      final double barHeight = (item.value.abs() / (maxValue - scaledMinValue)) * availableHeight * animationValue;

      // 绘制柱状图（垂直方向）
      final double barY = item.value >= 0
          ? zeroY - barHeight // 正值从0点向上
          : zeroY; // 负值从0点向下

      final rect = Rect.fromLTWH(
        xPos,
        barY,
        barWidth,
        barHeight,
      );
      canvas.drawRRect(
        RRect.fromRectAndRadius(rect, const Radius.circular(4)),
        barPaint,
      );

      // 绘制标签（日期）
      textPainter.text = TextSpan(
        text: item.label,
        style: textStyle,
      );
      textPainter.layout();
      textPainter.paint(
        canvas,
        Offset(
          xPos + (barWidth - textPainter.width) / 2,
          size.height - padding + labelPadding,
        ),
      );
    }

    // 绘制X轴标签（0点）
    textPainter.text = TextSpan(
      text: '0',
      style: textStyle.copyWith(fontWeight: FontWeight.bold),
    );
    textPainter.layout();
    textPainter.paint(
      canvas,
      Offset(
        padding - textPainter.width - labelPadding,
        zeroY - textPainter.height / 2,
      ),
    );
  }

  @override
  bool shouldRepaint(covariant BarChartPainter oldDelegate) {
    return oldDelegate.data != data || oldDelegate.animationValue != animationValue;
  }
}

class BarData {
  final String label;
  final double value;

  BarData(this.label, this.value);
}
